<template>
  <view class="comment-manage">
    <view class="page-header">
      <text class="page-title">评论管理</text>
      <text class="page-description">管理所有用户的评论内容，支持审核和删除操作</text>
    </view>
    
    <view class="action-bar">
      <view class="search-bar">
        <text class="bi bi-search"></text>
        <input 
          type="text" 
          v-model="searchKeyword" 
          placeholder="搜索评论内容或用户名" 
          @input="handleSearch"
        />
      </view>
      
      <view class="filter-bar">
        <view :class="['filter-item', { active: filter === 'all' }]" @click="setFilter('all')">全部</view>
        <view :class="['filter-item', { active: filter === 'pending' }]" @click="setFilter('pending')">待审核</view>
        <view :class="['filter-item', { active: filter === 'approved' }]" @click="setFilter('approved')">已通过</view>
        <view :class="['filter-item', { active: filter === 'rejected' }]" @click="setFilter('rejected')">已拒绝</view>
      </view>
    </view>
    
    <view class="comment-table" v-if="commentList.length > 0">
      <view class="table-header">
        <view class="th user-col">用户信息</view>
        <view class="th content-col">评论内容</view>
        <view class="th time-col">发布时间</view>
        <view class="th rating-col">评分</view>
        <view class="th status-col">状态</view>
        <view class="th action-col">操作</view>
      </view>
      <view class="table-body">
        <view v-for="comment in commentList" :key="comment._id" class="table-row">
          <view class="td user-col">
            <view class="user-info">
              <view class="user-avatar">
                <text>{{ getUserInitial(comment.userName) }}</text>
              </view>
              <view class="user-detail">
                <text class="user-name">{{ comment.userName }}</text>
                <text class="user-id">ID: {{ getShortId(comment._id) }}</text>
              </view>
            </view>
          </view>
          
          <view class="td content-col">
            <view class="comment-content">
              <text class="content-text">{{ comment.content }}</text>
              <text class="product-name" v-if="comment.productName">商品: {{ comment.productName }}</text>
            </view>
          </view>
          
          <view class="td time-col">
            <text>{{ formatDate(comment.createTime || comment.time) }}</text>
          </view>
          
          <view class="td rating-col">
            <uni-rate :value="comment.rating || 5" disabled size="15" />
          </view>
          
          <view class="td status-col">
            <view :class="['status-tag', getStatusClass(comment.status)]">
              {{ getStatusText(comment.status) }}
            </view>
          </view>
          
          <view class="td action-col">
            <view class="action-buttons">
              <text 
                :class="['action-btn approve', {'disabled': comment.status === 1}]" 
                @click="handleApprove(comment)"
              >通过</text>
              <text 
                :class="['action-btn reject', {'disabled': comment.status === 0}]"
                @click="handleReject(comment)"
              >拒绝</text>
              <text class="action-btn delete" @click="showDeleteConfirm(comment)">删除</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <view class="empty-state" v-else>
      <text class="bi bi-inbox empty-icon"></text>
      <text class="empty-text">暂无评论数据</text>
    </view>
    
    <view class="pagination" v-if="total > 0">
      <view class="page-info">
        <text>总计 {{ total }} 条评论，当前第 {{ currentPage }}/{{ totalPages }} 页</text>
      </view>
      <view class="page-controls">
        <text 
          :class="['page-btn prev', { disabled: currentPage <= 1 }]"
          @click="prevPage"
        >上一页</text>
        <view class="page-numbers">
          <text 
            v-for="page in displayedPages" 
            :key="page" 
            :class="['page-number', { active: currentPage === page }]"
            @click="goToPage(page)"
          >{{ page }}</text>
        </view>
        <text 
          :class="['page-btn next', { disabled: currentPage >= totalPages }]"
          @click="nextPage"
        >下一页</text>
      </view>
    </view>
    
    <!-- 删除确认弹窗 -->
    <uni-popup ref="deletePopup" type="dialog">
      <uni-popup-dialog
        title="删除确认"
        content="确定要删除此评论吗？此操作不可恢复。"
        confirmText="删除"
        cancelText="取消"
        @confirm="confirmDelete"
        @close="closeDeletePopup"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

const searchKeyword = ref('')
const commentList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const filter = ref('all')
const currentCommentToDelete = ref(null)
const deletePopup = ref(null)

const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value)
})

const displayedPages = computed(() => {
  const pages = []
  const maxDisplayPages = 5
  
  if (totalPages.value <= maxDisplayPages) {
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i)
    }
  } else {
    let startPage = Math.max(1, currentPage.value - 2)
    let endPage = Math.min(totalPages.value, startPage + maxDisplayPages - 1)
    
    if (endPage - startPage < maxDisplayPages - 1) {
      startPage = Math.max(1, endPage - maxDisplayPages + 1)
    }
    
    for (let i = startPage; i <= endPage; i++) {
      pages.push(i)
    }
  }
  
  return pages
})

const fetchCommentList = async () => {
  try {
    uni.showLoading({
      title: '加载中...'
    })
    
    let statusFilter = undefined
    if (filter.value === 'approved') statusFilter = 1
    if (filter.value === 'rejected') statusFilter = 0
    if (filter.value === 'pending') statusFilter = 2
    
    const res = await uniCloud.callFunction({
      name: 'comment',
      data: {
        body: JSON.stringify({
          action: 'getPosts',
          page: currentPage.value,
          pageSize: pageSize.value,
          keyword: searchKeyword.value,
          status: statusFilter
        })
      }
    })
    
    uni.hideLoading()
    
    if (res.result && res.result.status === 1) {
      commentList.value = res.result.data.list || []
      total.value = res.result.data.total || 0
      
      // 如果当前页没有数据且不是第一页，回到上一页
      if (commentList.value.length === 0 && currentPage.value > 1) {
        currentPage.value--
        fetchCommentList()
      }
    } else {
      uni.showToast({
        title: '获取评论列表失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('获取评论列表失败:', error)
    uni.showToast({
      title: '获取评论列表失败',
      icon: 'none'
    })
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchCommentList()
}

const setFilter = (newFilter) => {
  filter.value = newFilter
  currentPage.value = 1
  fetchCommentList()
}

const handleStatusChange = async (comment, newStatus) => {
  try {
    uni.showLoading({
      title: '更新中...'
    })
    
    const res = await uniCloud.callFunction({
      name: 'comment',
      data: {
        body: JSON.stringify({
          action: 'updateComment',
          postId: comment.postId,
          commentId: comment._id,
          commentData: {
            status: newStatus
          }
        })
      }
    })
    
    uni.hideLoading()
    
    if (res.result && res.result.status === 1) {
      uni.showToast({
        title: '状态更新成功',
        icon: 'success'
      })
      fetchCommentList()
    } else {
      uni.showToast({
        title: '更新失败: ' + (res.result?.message || '未知错误'),
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('更新评论状态失败:', error)
    uni.showToast({
      title: '更新评论状态失败',
      icon: 'none'
    })
  }
}

const handleApprove = (comment) => {
  if (comment.status !== 1) {
    handleStatusChange(comment, 1)
  }
}

const handleReject = (comment) => {
  if (comment.status !== 0) {
    handleStatusChange(comment, 0)
  }
}

const showDeleteConfirm = (comment) => {
  currentCommentToDelete.value = comment
  deletePopup.value.open()
}

const closeDeletePopup = () => {
  currentCommentToDelete.value = null
}

const confirmDelete = async () => {
  if (!currentCommentToDelete.value) return
  
  try {
    uni.showLoading({
      title: '删除中...'
    })
    
    const res = await uniCloud.callFunction({
      name: 'comment',
      data: {
        body: JSON.stringify({
          action: 'deleteComment',
          postId: currentCommentToDelete.value.postId,
          commentId: currentCommentToDelete.value._id
        })
      }
    })
    
    uni.hideLoading()
    
    if (res.result && res.result.status === 1) {
      uni.showToast({
        title: '删除成功',
        icon: 'success'
      })
      fetchCommentList()
    } else {
      uni.showToast({
        title: '删除失败: ' + (res.result?.message || '未知错误'),
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('删除评论失败:', error)
    uni.showToast({
      title: '删除评论失败',
      icon: 'none'
    })
  }
  
  currentCommentToDelete.value = null
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    fetchCommentList()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    fetchCommentList()
  }
}

const goToPage = (page) => {
  if (page !== currentPage.value) {
    currentPage.value = page
    fetchCommentList()
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '未知时间'
  
  const date = new Date(dateString)
  const now = new Date()
  const diff = now - date
  
  // 时间差小于1天，显示相对时间
  if (diff < 24 * 60 * 60 * 1000) {
    if (diff < 60 * 1000) {
      return '刚刚'
    } else if (diff < 60 * 60 * 1000) {
      return `${Math.floor(diff / (60 * 1000))}分钟前`
    } else {
      return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
    }
  } else if (diff < 30 * 24 * 60 * 60 * 1000) {
    // 时间差小于30天，显示天数
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
  } else {
    // 否则显示完整日期
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }
}

const getUserInitial = (userName) => {
  return userName ? userName.substring(0, 1).toUpperCase() : 'U'
}

const getShortId = (id) => {
  return id ? id.substring(id.length - 6) : ''
}

const getStatusClass = (status) => {
  if (status === 1) return 'approved'
  if (status === 0) return 'rejected'
  return 'pending'
}

const getStatusText = (status) => {
  if (status === 1) return '已通过'
  if (status === 0) return '已拒绝'
  return '待审核'
}

onMounted(() => {
  fetchCommentList()
})
</script>

<style lang="scss" scoped>
.comment-manage {
  .page-header {
    margin-bottom: 30rpx;
    
    .page-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 10rpx;
      display: block;
    }
    
    .page-description {
      font-size: 26rpx;
      color: #999;
    }
  }
  
  .action-bar {
    display: flex;
    flex-direction: column;
    margin-bottom: 30rpx;
    
    .search-bar {
      display: flex;
      align-items: center;
      background-color: #fff;
      border-radius: 10rpx;
      padding: 0 20rpx;
      margin-bottom: 20rpx;
      height: 80rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
      
      .bi {
        font-size: 32rpx;
        color: #999;
        margin-right: 10rpx;
      }
      
      input {
        flex: 1;
        height: 80rpx;
        font-size: 28rpx;
      }
    }
    
    .filter-bar {
      display: flex;
      background-color: #fff;
      border-radius: 10rpx;
      overflow: hidden;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
      
      .filter-item {
        flex: 1;
        text-align: center;
        padding: 20rpx 0;
        font-size: 28rpx;
        color: #666;
        position: relative;
        transition: all 0.3s;
        
        &.active {
          color: #1890ff;
          font-weight: 500;
          
          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 40rpx;
            height: 4rpx;
            background-color: #1890ff;
            border-radius: 2rpx;
          }
        }
      }
    }
  }
  
  .comment-table {
    background-color: #fff;
    border-radius: 10rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
    margin-bottom: 30rpx;
    
    .table-header {
      display: flex;
      background-color: #fafafa;
      
      .th {
        padding: 24rpx 16rpx;
        font-size: 26rpx;
        color: #333;
        font-weight: 600;
      }
    }
    
    .table-body {
      .table-row {
        display: flex;
        border-bottom: 1rpx solid #f0f0f0;
        transition: all 0.3s;
        
        &:hover {
          background-color: #f9f9f9;
        }
        
        &:last-child {
          border-bottom: none;
        }
        
        .td {
          padding: 20rpx 16rpx;
          font-size: 26rpx;
          color: #666;
        }
      }
    }
    
    .user-col {
      width: 200rpx;
      flex-shrink: 0;
    }
    
    .content-col {
      flex: 1;
    }
    
    .time-col {
      width: 120rpx;
      flex-shrink: 0;
    }
    
    .rating-col {
      width: 150rpx;
      flex-shrink: 0;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .status-col {
      width: 100rpx;
      flex-shrink: 0;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .action-col {
      width: 200rpx;
      flex-shrink: 0;
    }
    
    .user-info {
      display: flex;
      align-items: center;
      
      .user-avatar {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        background-color: #1890ff;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 10rpx;
        
        text {
          color: #fff;
          font-size: 26rpx;
          font-weight: 500;
        }
      }
      
      .user-detail {
        display: flex;
        flex-direction: column;
        
        .user-name {
          font-size: 26rpx;
          color: #333;
          font-weight: 500;
          margin-bottom: 4rpx;
        }
        
        .user-id {
          font-size: 22rpx;
          color: #999;
        }
      }
    }
    
    .comment-content {
      display: flex;
      flex-direction: column;
      
      .content-text {
        font-size: 26rpx;
        color: #333;
        line-height: 1.5;
        margin-bottom: 8rpx;
        word-break: break-all;
      }
      
      .product-name {
        font-size: 22rpx;
        color: #1890ff;
      }
    }
    
    .status-tag {
      display: inline-block;
      padding: 4rpx 16rpx;
      border-radius: 20rpx;
      font-size: 22rpx;
      
      &.approved {
        background-color: rgba(82, 196, 26, 0.1);
        color: #52c41a;
      }
      
      &.rejected {
        background-color: rgba(245, 34, 45, 0.1);
        color: #f5222d;
      }
      
      &.pending {
        background-color: rgba(250, 173, 20, 0.1);
        color: #faad14;
      }
    }
    
    .action-buttons {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      align-items: center;
      .action-btn {
        margin: 0 6rpx;
        padding: 6rpx 16rpx;
        font-size: 24rpx;
        border-radius: 6rpx;
        transition: all 0.3s;
        
        &.approve {
          color: #52c41a;
          background-color: rgba(82, 196, 26, 0.1);
          
          &:active {
            background-color: rgba(82, 196, 26, 0.2);
          }
        }
        
        &.reject {
          color: #f5222d;
          background-color: rgba(245, 34, 45, 0.1);
          
          &:active {
            background-color: rgba(245, 34, 45, 0.2);
          }
        }
        
        &.delete {
          color: #666;
          background-color: rgba(0, 0, 0, 0.05);
          
          &:active {
            background-color: rgba(0, 0, 0, 0.1);
          }
        }
        
        &.disabled {
          opacity: 0.5;
          pointer-events: none;
        }
      }
    }
  }
  
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    border-radius: 10rpx;
    padding: 60rpx 0;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
    
    .empty-icon {
      font-size: 100rpx;
      color: #ddd;
      margin-bottom: 20rpx;
    }
    
    .empty-text {
      font-size: 28rpx;
      color: #999;
    }
  }
  
  .pagination {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20rpx 0;
    
    .page-info {
      margin-bottom: 16rpx;
      
      text {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .page-controls {
      display: flex;
      align-items: center;
      
      .page-btn {
        padding: 10rpx 20rpx;
        font-size: 26rpx;
        background-color: #fff;
        color: #333;
        border-radius: 6rpx;
        margin: 0 10rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
        
        &.disabled {
          opacity: 0.5;
          pointer-events: none;
        }
      }
      
      .page-numbers {
        display: flex;
        
        .page-number {
          width: 60rpx;
          height: 60rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 26rpx;
          color: #666;
          margin: 0 8rpx;
          border-radius: 6rpx;
          
          &.active {
            background-color: #1890ff;
            color: #fff;
            box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.2);
          }
        }
      }
    }
  }
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .comment-manage {
    .table-header .th, .table-body .td {
      padding: 16rpx 12rpx;
      font-size: 24rpx;
    }
    
    .time-col {
      display: none;
    }
  }
}
</style> 